package com.olive.handler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.olive.response.Result;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class CommonLoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
	
	@Value("${spring.security.loginType}")
	private String loginType;
	@Autowired
	private ObjectMapper objectMapper;
	
	
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
										HttpServletResponse response,
										Authentication authentication) throws IOException, ServletException {
//		Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
//		Optional<String> auth = authorities.stream().map(GrantedAuthority::getAuthority).filter(a -> a.equals("read")).findFirst();
//		log.info("auth:{}",authorities);
//		if(auth.isPresent()){
//			log.info("您有足够的权限访问此资源");
//			response.sendRedirect("/user/hello");
//		}else {
//			log.info("您没有足够的权限访问此资源");
//			response.sendRedirect("/user/error");
//		}

		if ("JSON".equalsIgnoreCase(loginType)){
			response.setContentType("application/json;charset=utf-8");
			response.getWriter().write(objectMapper.writeValueAsString(Result.ok()));
		}else {
			//跳转到上一次请求的页面上
			super.onAuthenticationSuccess(request, response, authentication);
		}
	}
}



